<?php

$__FILEPATH__ = dirname(__FILE__)."/";
require_once($__FILEPATH__."./func_common.php");
require_once($__FILEPATH__."./class_def.php");
require_once($__FILEPATH__."./conf/info.php");
session_start();
if (!isset($_SESSION["user"]))
{
	header("Location: ./loginpage.php");
	exit(0);
}

header("Content-Type: text/html; charset=UTF-8");

$mysqli = GetMysqliInstance();

$PageArray = array();
$PageArray["algo_classlist"] = array();

$result = $mysqli->query("select * from classlist where type='algorithm'", MYSQLI_USE_RESULT);
if ($result)
{
	while($row = $result->fetch_array(MYSQLI_ASSOC))
	{
		$ClassItem = new ClassListItem;
		$ClassItem->id 		= intval($row["id"]);
		$ClassItem->type 	= $row["type"];
		$ClassItem->name 	= $row["name"];
		$ClassItem->cnt 	= intval($row["cnt"]);
		$ClassItem->intra 	= $row["intra"];
		$PageArray["algo_classlist"][] = $ClassItem;
	}

	$result->close();
}


if (isset($_POST["blog_add"]))
{
	if ($_POST["title"] == "" || $_POST["keyword"] == "")
		die("标题或关键字不能为空");

	$user = $_SESSION["user"];
	$title = htmlspecialchars($_POST["title"]);
	$keyword = htmlspecialchars($_POST["keyword"]);
	$content = $_POST["editor"];
	
	$in_ip = GetRequestIP();
	$in_time = GetSysTime();
	$permission = "public";

	if ($keyword[strlen($keyword) - 1] != '|')
		$keyword .= "|";

	$stmt = $mysqli->prepare("insert into BlogList(user, title, keyword, content, in_ip, in_time, permission) values(?, ?, ?, ?, ?, ?, ?)");
	$stmt->bind_param("sssssss", $user, $title, $keyword, $content, $in_ip, $in_time, $permission);
	$ret = $stmt->execute();
	$stmt->close();
	if (!$ret)
		die("系统出错添加失败~");
	
	$result = $mysqli->query("select LAST_INSERT_ID()");
	if (!$result)
		die("系统出错添加失败~");

	if (!($row = $result->fetch_array(MYSQLI_NUM)))
	{
		$result->close();
		die("系统出错添加失败~");
	}
	
	$id = $row[0];
	$result->close();

	$class_select = false;
	foreach ($PageArray["algo_classlist"] as $Object)
	{
		if (isset($_POST["$Object->id"]))
		{
			$class_select = true;
			$mysqli->query("insert into BCLinkList values($id, $Object->id)");
			$mysqli->query("update classlist set cnt = cnt + 1 where id = $Object->id");
		}
	}

	if (!$class_select)
	{
		$mysqli->query("insert into BCLinkList values($id, 0)");
	}

	ClientRedirect("./blog_home.php", "文章添加成功！");

	exit(0);
}




$mysqli->close();

?>